package GUI;


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JWindow;

import voting.ClientVoting;

import network.Client;
import network.Operations;


import com.toedter.calendar.JCalendar;

import entities.Candidate;
import entities.User;

public class CreateVotingPanel  extends JPanel implements ActionListener,PropertyChangeListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
     
	JLabel title;
	JLabel question;
	JLabel start;
	JLabel end;
	JLabel successMessage;
	JLabel candidate;
	JLabel program;
	
	JTextField questionField;
	JTextField startField;
	JTextField endField;
	JTextField candidateField;
	
	JTextArea candidateProgram;
	
	JButton createButton;
	JButton startButton;
	JButton endButton;
	JButton candidateButton;
	
    
	ArrayList<Candidate> candidatesA;
	
	Calendar calendar;
	JTextField dateField;
	
	
	JPanel popup1;
	JPanel popup2;
	
	JList candidatesList;
	JScrollPane scroll;
	DefaultListModel listModel;
	
	boolean isOpen;
	Calendar startDate;
	Calendar endDate;
	Calendar date;
	
	
	
	

	public CreateVotingPanel()
	{
		isOpen=false;
		calendar = Calendar.getInstance();
		startDate=Calendar.getInstance();
		endDate=Calendar.getInstance();
		
		
		setBounds(0,0,700,500);
	

		candidatesA=new ArrayList<Candidate>();
	
		
		setLayout(null);
		
		title=new JLabel("New Voting");
		title.setBounds(20,20,100,30);
		
		
		question=new JLabel("Question: ");
		question.setBounds(100,70,100,30);
		
		successMessage=new JLabel("");
		successMessage.setBounds(150, 450, 250, 30);
		
		
		
		start=new JLabel("Start Date: ");
		start.setBounds(100,130,100,30);
		
		end=new JLabel("End Date: ");
		end.setBounds(100,160,100,30);
		
		candidate=new JLabel("Candidates: ");
		candidate.setBounds(100,190,100,30);
		listModel=new DefaultListModel();
		candidatesList=new JList(listModel);
		candidatesList.setSize(200,30);
		scroll=new JScrollPane(candidatesList);
		scroll.setBounds(250,350,200,150);
		scroll.setAutoscrolls(true);
		candidateField=new JTextField();
		candidateField.setBounds(250,190,145,25);
		candidateButton=new JButton("Add");
		candidateButton.setBounds(400, 190, 65, 25);
		candidateButton.addActionListener(this);
		candidateProgram=new JTextArea();
		candidateProgram.setBounds(250,220,145,110);
		program=new JLabel("Candidate Program: ");
		program.setBounds(70,220,130,30);
		
		questionField=new JTextField();
		questionField.setBounds(250, 70, 200, 25);
		
		startField=new JTextField();
		startField.setBounds(250,130,145,25);
		startField.setEditable(false);
		DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,new Locale("english"));
		startField.setText(df.format(Calendar.getInstance().getTime()));
		
		endField=new JTextField();
		endField.setBounds(250,160,145,25);
		endField.setEditable(false);
		endField.setText(df.format(Calendar.getInstance().getTime()));
		
		createButton=new JButton("Save Voting");
		createButton.setBounds(200, 530, 150, 30);
		createButton.addActionListener(this);
	
		
		startButton=new JButton();
		startButton.setIcon(new ImageIcon("calendar_icon.gif"));
		startButton.setBounds(400, 130, 30, 25);
		startButton.addActionListener(this);
		
	
		
		endButton=new JButton();
		endButton.setIcon(new ImageIcon("calendar_icon.gif"));
		endButton.setBounds(400, 160, 30, 25);
		endButton.addActionListener(this);
		
		
		
		popup1=new JPanel();
		
		popup1.setBounds(27+ (startButton.getX()),(startButton.getY()), 230, 190);
		popup1.setVisible(false);
		
		
		
		JCalendar jcalendar1=new JCalendar();
		jcalendar1.setCalendar(calendar);
		jcalendar1.setLocale(new Locale("english"));
		jcalendar1.addPropertyChangeListener(this);
		jcalendar1.setBackground(Color.WHITE);
		popup1.add(jcalendar1);
		popup1.setBackground(Color.WHITE);
		
		popup2=new JPanel();
		
		popup2.setBounds(27+ (endButton.getX()),(endButton.getY()), 230, 190);
		popup2.setVisible(false);
		
		
		JCalendar jcalendar2=new JCalendar();
		jcalendar2.setCalendar(calendar);
		jcalendar2.setLocale(new Locale("english"));
		jcalendar2.addPropertyChangeListener(this);
		jcalendar2.setBackground(Color.WHITE);
		popup2.add(jcalendar2);
		popup2.setBackground(Color.WHITE);
		
		add(popup1);
		add(popup2);
	
		add(title);
		add(successMessage);
		add(candidate);
		
		add(question);
		add(questionField);
		
		add(createButton);
		
		add(startButton);
		add(startField);
		add(start);
		
		add(endButton);
		add(endField);
		add(end);
		
		add(candidateField);
		add(candidateButton);
		add(scroll);
		add(candidateProgram);
		add(program);
		
		
	}
	public void viewPicker(boolean isStart)
	{
/*		if(isStart)
			datePicker.setBounds(350,100,230,150);
		else
			datePicker.setBounds(350,200,230,150);
		calendar=new JCalendar();
		calendar.setLocale(new Locale("english"));
		add(datePicker);*/
		
		
	}
	
	public static void main(String[]args)
	{
		/*JFrame frame=new JFrame();
		frame.setBounds(0,0,750,550);
		frame.setContentPane(new CreateVotingPanel());
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		*/
		
	}
	@Override
	public void actionPerformed(ActionEvent ev) {
		
		if(!isOpen)
		{
			if(ev.getSource()==startButton)
			{
				//startButton.setText("Done");
				
				//have to be from start of the main frame
			   
			    popup1.setVisible(true);
				
				
			    isOpen=true;
				
				dateField=startField;
				date=startDate;
			}
			else
				if(ev.getSource()==endButton)
				{
					//endButton.setText("Done");
					popup2.setVisible(true);
					isOpen=true;
					dateField=endField;
					date=endDate;
				}
			else
				if(ev.getSource()==createButton)
				{
					if(checkInput())
				    addVoting();
					
						
					//System.out.println(startDate.get(Calendar.DAY_OF_MONTH)+" "+(startDate.get(Calendar.MONTH)+1)+" "+startDate.get(Calendar.YEAR)+" "+endDate.get(Calendar.DAY_OF_MONTH)+" "+(endDate.get(Calendar.MONTH)+1)+" "+endDate.get(Calendar.YEAR));
				}
			else
				if(ev.getSource()==candidateButton)
				{
					if(candidateField.getText()==null||candidateField.getText().equals(""))
					{
						JOptionPane.showMessageDialog(null, "Please enter candidate name");
					}
					else
					{
					int pos=candidatesList.getModel().getSize();
					listModel.add(pos, "Candidate "+(pos+1)+": "+candidateField.getText());
					Candidate temp=new Candidate();
					temp.setName(candidateField.getText());
					temp.setProgram(candidateProgram.getText());
					candidatesA.add(temp);
					candidateField.setText("");
					candidateProgram.setText("");
					}
					
				}
				
		}
		else
		{
			//startButton.setText("Edit");
			
			//endButton.setText("Edit");
			popup1.setVisible(false);
			popup2.setVisible(false);
			isOpen=false;
			
		}
		
	}
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if(evt.getPropertyName().equals("calendar"))
		{
			DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,new Locale("english"));
			Calendar calendar1 = (Calendar) evt.getNewValue();
			dateField.setText(df.format(calendar1.getTime()));
			date.setTime(calendar1.getTime());
		}
		
	}
	
	public boolean checkInput()
	{
		JDialog error=new JDialog();
		error.setBounds(250,250, 300, 200);
		error.getContentPane().setLayout(new GridLayout(5,0));
	
		boolean isStartAfterNow=checkStartNow();
		boolean isEndAfterStart=checkStartEnd();
		boolean hasCandidates=checkCandidates();
		boolean hasQuestion=checkQuestion();
		JLabel sn=new JLabel("Start date should be after today");
		sn.setForeground(Color.RED);
		
		JLabel se=new JLabel("End date should be after start date");
		se.setForeground(Color.RED);
		
		JLabel c=new JLabel("At least one candidate should be added");
		c.setForeground(Color.RED);
		
		JLabel q=new JLabel("Question is missing");
		q.setForeground(Color.RED);
		
		error.getContentPane().add(new JLabel("Invalid input"));
		if(!isStartAfterNow)
			error.getContentPane().add(sn);
		if(!isEndAfterStart)
			error.getContentPane().add(se);
		if(!hasCandidates)
			error.getContentPane().add(c);
		if(!hasQuestion)
			error.getContentPane().add(q);
       boolean flag= isStartAfterNow&isEndAfterStart&hasCandidates&hasQuestion;
       if(!flag)
    	   error.setVisible(true);
       return flag;
       
		
	}
	public boolean checkStartNow()
	{
		//successMessage.setText(startDate.before(Calendar.getInstance().getTime())+" ");
		//return startDate.after(Calendar.getInstance().getTime());
		return true;
	}
	
	public boolean checkStartEnd()
	{
		return startDate.before(endDate);
	}
	public boolean checkCandidates()
	{
		return listModel.getSize()>0;
	}
	public boolean checkQuestion()
	{
		return questionField.getText()!=null&&questionField.getText().length()>0;
	}
	
	
	public void addVoting()
	{
		Candidate[] candidates=getCandidatesFromList();
		System.out.println("here");
		//Client.client.receiveMessage();
		System.out.println("there");
		boolean flag=ClientVoting.createVoting(startDate.get(Calendar.DAY_OF_MONTH),(startDate.get(Calendar.MONTH)+1),startDate.get(Calendar.YEAR),endDate.get(Calendar.DAY_OF_MONTH),(endDate.get(Calendar.MONTH)+1),endDate.get(Calendar.YEAR), new User[10],candidates, questionField.getText(), 1);
		String text=flag?"Voting created successfully":"Failed to create voting";
		if(!flag)
		successMessage.setText(text);
		else
		{
			successMessage.setText("");
			JOptionPane.showMessageDialog(null, text);
			MainFrame.getMainFrame().remove(this);
			MainFrame.getMainFrame().addViewVotingPnl(true);
		}
	}
	
	public Candidate[] getCandidatesFromList()
	{
		Candidate[] candidates=new Candidate[listModel.getSize()];
		
		for(int i=0;i<candidates.length;i++)
		{
			candidates[i]=candidatesA.get(i);
			System.out.println(candidatesA.get(i));
		}
		return candidates;
	}
}
